import React, { useEffect, useState } from 'react'
import { EditOutlined, DeleteOutlined, UploadOutlined } from '@ant-design/icons'
import { Button, Table, Tag, Modal, message, notification } from 'antd'
import { connect, NavLink, useNavigate } from 'umi'
import { useRequest } from 'ahooks';
import axios from 'axios';
import _ from 'lodash'
import type { NotificationPlacement } from 'antd/es/notification/interface';

// 发起网络请求，通过更新新闻信息
const updateNewsRequest = (item: any, id: string | number | undefined) => {
    return axios.patch(`http://localhost:3000/news/${id}`, {
        ...item
    })
}
function Draft(props: any) {
    // props中解构出 dispatch 和 newsList 属性
    const { dispatch, newsList, currentUserNewsList } = props;
    // 表格的loading
    const [loading, setLoading] = useState(false);
    // 删除按钮对话框是否显示，初始为false，不显示
    const [deleteOpen, setDeleteOpen] = useState(false);
    //删除对话框的异步操作等待的loading
    const [DelConfirmLoading, setDelConfirmLoading] = useState(false);
    // 保存选中的item数据
    const [currentItem, setCurrentItem] = useState(null);
    const navigate = useNavigate();
    // 从本地存储中获取当前用户信息
    const currentUserData: Array<any> = JSON.parse(localStorage.getItem('token') as string);
    useEffect(() => {
        setLoading(true);
        dispatch({
            type: 'StandBox/getCurrentUserNewsList',
            payload: {
                setLoading,
                currentUser: currentUserData,
                auditState: 0
            }
        })

    }, [])

    // useRequest - 更新当前id新闻信息
    const { run: UpdateCurrentNewsData, loading: updateLoading } = useRequest(updateNewsRequest, {
        throttleWait: 300,
        manual: true,
        onSuccess: (result: any, params) => {
            if (result.status === 200) {
                // 跳转到草稿箱页面或者审核列表
                // console.log(params);
                openNotification('bottomRight', params[0].auditState * 1);
                if (params[0].auditState * 1 === 0) {
                    navigate(`/news-manage/draft`);
                }
                else if (params[0].auditState * 1 === 1) {
                    navigate(`/audit-manage/list`);
                }

            }
        },
        onError(e, params) {
            message.warning('请求新闻数据失败')
        },
    })
    //#region 消息通知框
    const openNotification = (placement: NotificationPlacement, publishState: number) => {
        notification.open({
            message: `通知`,
            description: `你可以到${publishState === 0 ? '草稿箱' : '审核列表'}中查看您的新闻`,
            placement,
            onClick: () => {
                console.log('Notification Clicked!');
            },
        });
    };
    //#endregion
    //表格中删除按钮，删除对应的新闻信息
    const handelDeleteNews = (item: any) => {
        // 显示表格loading
        setLoading(true);
        // 显示删除对话框异步操作loading
        setDelConfirmLoading(true);
        // 删除新闻对应信息
        handleDeleteConfirm(item);
    };

    // 删除对话框的确认，执行回调函数
    const handleDeleteConfirm = async (item: any) => {
        // 当前页面同步状态+后台同步
        await dispatch({
            type: 'StandBox/deleteNewsList',
            payload: {
                newsItem: item,
                setLoading,
                setDeleteOpen,
                setDelConfirmLoading,
                auditState: 0,
                currentUser: currentUserData,
            }
        })

    };
    // 删除对话框的取消，执行回调函数
    const handleDeleteCancel = () => {
        console.log('取消操作');
        // 取消操作，关闭删除对话框
        setDeleteOpen(false);
    };
    //提交审核
    const handelSubmitReview = (auditState: number, id: string) => {
        const newItem: any = {
            "auditState": auditState,//审核状态。初始为0
        }
        // if(auditState===1){
        //     newItem.publishState=1;
        // }
        // 更新新闻信息并且跳到对应页面
        UpdateCurrentNewsData(newItem, id);

    };
    //表格列的配置描述
    const columns = [
        {
            title: 'ID',    //标题
            dataIndex: 'id',     //匹配的字段名 
            key: 'id',
            render: (id: string) => {
                return <b>{id}</b>
            }
        },
        {
            title: '新闻标题',
            dataIndex: 'title',
            key: 'title',
            render: (title: string, item: any) => {
                // dispatch({
                //     type: 'StandBox/getCurrentNewsDetail',
                //     payload: {
                //         id:item.id
                //     }
                // })
                return <NavLink to={`/news-manage/preview/${item.id}`}>{title}</NavLink>
            }
        },
        {
            title: '作者',
            dataIndex: 'author',
            key: 'author',
        },
        {
            title: '分类',
            dataIndex: 'category',
            key: 'category',
            render: (category: any) => category.title
        },
        {
            title: '操作',
            render: (item: any) => {
                return (<div>
                    <>
                        <Button danger shape="circle" style={{ 'marginRight': '10px' }} icon={<DeleteOutlined />} onClick={() => {
                            setCurrentItem(item);
                            setDeleteOpen(true);
                        }}></Button>
                    </>
                    <Button type="primary" shape="circle" icon={<EditOutlined />} style={{ 'marginRight': '10px' }}
                        onClick={() => {
                            dispatch({
                                type: 'StandBox/getCurrentNewsDetail',
                                payload: {
                                    id: item.id
                                }
                            })
                            navigate(`/news-manage/update/${item.id}`)
                        }} ></Button>
                    <Button type="primary" shape="circle" icon={<UploadOutlined />} onClick={() => { handelSubmitReview(1, item.id) }} ></Button>
                </div>)
            }
        },
    ];

    return (
        <div>
            <Table dataSource={currentUserNewsList} columns={columns} loading={loading} sticky scroll={{ y: '63vh' }} rowKey={(item) => item.id} />
            {/* 删除的对话框 */}
            <Modal
                title={`【${(currentItem as any)?.title}】删除`}
                open={deleteOpen}
                onOk={() => { handelDeleteNews(currentItem) }}
                confirmLoading={DelConfirmLoading}
                // mask={false}
                onCancel={handleDeleteCancel}
                okText='确定'
                cancelText='取消'
            >
                <p>是否要删除该新闻</p>
            </Modal>
        </div>
    )
}

const mapStateToProps = (state: any) => {
    return {
        newsList: state.StandBox.newsList,
        currentUserNewsList: state.StandBox.currentUserNewsList,
    }
}
export default connect(mapStateToProps)(Draft)
